<template>
	<div>
		<!-- 面包屑 -->
		<el-breadcrumb separator-class="el-icon-arrow-right">
			<el-breadcrumb-item :to="{ path: '/layout' }">首页</el-breadcrumb-item>
			<el-breadcrumb-item>角色管理</el-breadcrumb-item>
			<el-breadcrumb-item>角色列表</el-breadcrumb-item>
		</el-breadcrumb>
		<!-- 卡片布局 -->
		<el-card>
			<!-- 植入搜索栏 -->
			<el-row :gutter="20">
				<el-col :span="5"><el-input clearable placeholder="搜索名称" v-model="searchName" clearableclear="getRoleList"></el-input></el-col>
				<el-col :span="5"><el-input clearable placeholder="搜索明细" v-model="searchDesc" clearableclear="getRoleList"></el-input></el-col>

				<el-col :span="2">
					<el-button type="primary" @click="getRoleList()">
						<el-icon><Search /></el-icon>
					</el-button>
				</el-col>
				<el-col :span="5"><el-button type="primary" @click="showAddBox = true">添加角色</el-button></el-col>
			</el-row>
			<!-- 放入table -->
			<el-table
				:data="roleList"
				style="width: 100%; height: 550px; margin-top:10px;"
				border
				:header-cell-style="{ height: '37px', padding: '0' }"
				:row-style="{ height: '37px' }"
				:cell-style="{ padding: '0' }"
			>
				<!-- 数据绑定 -->
				<el-table-column  label="角色id" width="80" prop="id"></el-table-column>
				<el-table-column  label="角色名称" width="100" prop="roleName"></el-table-column>
				<el-table-column label="用户权限" width="120" prop="roleAuth"></el-table-column>
				<el-table-column label="角色明细" width="180" prop="roleDesc"></el-table-column>
				<el-table-column label="可用性" width="100" prop="enable">
					<template #default="scope">
						<el-select @change="changeEnableOrLock(scope.row, true)" class="el-col-sm-22" size="small" v-model="scope.row.enable">
							<el-option v-for="item in enableOptions" :key="item.value" :label="item.label" :value="item.value" />
						</el-select>
					</template>
				</el-table-column>
				<el-table-column label="是否锁定" width="100" prop="lockable">
					<template #default="scope">
						<el-select @change="changeEnableOrLock(scope.row, false)" class="el-col-sm-22" size="small" v-model="scope.row.lockable">
							<el-option v-for="item in lockableOptions" :key="item.value" :label="item.label" :value="item.value" />
						</el-select>
					</template>
				</el-table-column>

				<el-table-column label="创建者" width="80" prop="createBy"></el-table-column>
				<el-table-column label="创建时间" width="200" prop="createDate"></el-table-column>
				<el-table-column label="最近修改人" width="100" prop="updateBy"></el-table-column>

				<el-table-column label="最近修改" width="250" prop="lastUpdate"></el-table-column>

				<el-table-column fixed="right" label="操作" width="300">
					<template #default="scope">
						<el-button size="small" @click="showEdit(scope.row)">编辑</el-button>
						<el-button size="small" type="primary" @click="showAuth(scope.row)">权限管理</el-button>
						<el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>

			<!-- 分页模块 -->
			<el-pagination
				v-model:current-page="pageNo"
				v-model:page-size="pageSize"
				:page-sizes="[10, 20, 50, 100]"
				:small="false"
				:disabled="false"
				:background="true"
				layout="total, sizes, prev, pager, next"
				:total="totalCount"
				@size-change="onSizeChange"
				@current-change="onPageChange"
			/>

			<!-- 添加会话框 -->
			<el-dialog title="添加角色对话框" v-model="showAddBox" width="30%" :before-close="clearEdit" style="padding: 8px 15px;" @close="onClose">
				<el-form :model="roleForm" :rules="roleFormRules" ref="roleFormRules" label-width="120px">
					<el-form-item label="角色名称" prop="roleName"><el-input v-model="roleForm.roleName"></el-input></el-form-item>
					<el-form-item label="角色权限" prop="roleAuth"><el-input v-model="roleForm.roleAuth"></el-input></el-form-item>
					<el-form-item label="角色明细" prop="roleDesc"><el-input v-model="roleForm.roleDesc"></el-input></el-form-item>

					<el-form-item class="dialog-footer">
						<el-button @click="clearEdit">取消</el-button>
						<el-button type="primary" @click="saveRoleData('roleFormRules')">确定</el-button>
					</el-form-item>
				</el-form>
			</el-dialog>

			<!-- 添加会话框 -->
			<el-dialog title="编辑角色" v-model="showEditBox" width="30%" :before-close="clearEdit" style="padding: 8px 15px;" @close="onClose">
				<el-form :model="roleForm" :rules="roleFormRules" ref="roleFormRules" label-width="120px">
					<el-form-item label="角色名称" prop="roleName"><el-input v-model="roleForm.roleName"></el-input></el-form-item>
					<el-form-item label="角色权限" prop="roleAuth"><el-input v-model="roleForm.roleAuth"></el-input></el-form-item>
					<el-form-item label="角色明细" prop="roleDesc"><el-input v-model="roleForm.roleDesc"></el-input></el-form-item>

					<el-form-item class="dialog-footer">
						<el-button @click="clearEdit">取消</el-button>
						<el-button type="primary" @click="saveRoleData('roleFormRules')">确定</el-button>
					</el-form-item>
				</el-form>
			</el-dialog>

			<!-- 角色权限框 -->
			<el-dialog title="编辑角色权限" v-model="showAuthMenu" :before-close="clearEdit" style="padding: 8px 15px;" @close="onClose">
				<el-table row-key="id" ref="tableRef" :data="menuList" style="width: 100%" height="500" default-expand-all @selection-change="handleSelectionChange" tooltip-effect="dark">
					<el-table-column type="selection" :reserve-selection="true"  />
					<!-- 数据展示列 -->
					<el-table-column  label="菜单id" width="100" prop="id"></el-table-column>
					<el-table-column  label="路由名称" width="100" prop="name"></el-table-column>
					<el-table-column label="父级菜单id" width="120" prop="parentId"></el-table-column>
					<el-table-column label="菜单名称" width="120" prop="menuName"></el-table-column>
					<el-table-column label="路径" width="150" prop="path"></el-table-column>
					<el-table-column label="组件地址" width="200" prop="component"></el-table-column>
					<el-table-column label="图标" width="80" prop="icon"></el-table-column>
				</el-table>

				<div style="margin-top: 20px">
					<el-button type="info" @click="toggleSelection()">清空选择</el-button>
					<el-button type="primary" @click="handleAuth()">确定</el-button>
				</div>
			</el-dialog>
		</el-card>
	</div>
</template>
<script>
import { getMenuList } from '@/api/menu';
import { getRoleList, addRole, deleteRole, showAuth, changeAuth } from '@/api/role.js';
import { Search } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';

export default {
	name: 'roleList',

	data() {
		return {
			enableOptions: [
				{
					value: '0',
					label: '是'
				},
				{
					value: '1',
					label: '否'
				}
			],
			lockableOptions: [
				{
					value: '1',
					label: '是'
				},
				{
					value: '0',
					label: '否'
				}
			],

			showAuthMenu: false,
			showEditBox: false,
			showAddBox: false,
			searchStr: '',
			pageNo: 1,
			pageSize: 10,
			totalCount: 0,

			searchDesc: '',
			searchName: '',

			roleForm: {
				id: '',
				roleName: '',
				roleAuth: '',
				roleDesc: ''
			},

			trigger: 'blur',
			roleFormRules: {
				roleName: [
					{
						required: true,
						message: '请输入角色名',
						trigger: 'blur'
					}
				],
				roleAuth: [
					{
						required: true,

						message: '请输入角色权限',
						trigger: 'blur'
					}
				],
				roleDesc: [
					{
						required: true,
						message: '请输入角色明细',
						trigger: 'blur'
					}
				]
			},

			roleList: [],
			menuList: [],
			roleAuthList: [],
			role: '',

			multipleSelection: []
		};
	},
	methods: {
		getRoleList() {
			this.searchStr = {
				desc: this.searchDesc,
				name: this.searchName
			};
			const param = { page: this.pageNo, limit: this.pageSize, searchStr: this.searchStr };
			getRoleList(param).then(resp => {
				this.totalCount = resp.total;
				this.roleList = resp.rows;
			});
		},
		saveRoleData(formname) {
			this.$refs[formname].validate(valid => {
				if (valid) {
					console.log('验证通过');
					this.$confirm('此操作将添加该角色, 是否继续?', '提示', {
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning'
					})
						.then(() => {
							addRole(this.roleForm).then(resp => {
								this.showAddBox = false;
								this.roleForm = [];
								this.getRoleList();
							});
						})
						.catch(() => {
							// console.log(message)
							this.$message({
								type: 'error',
								message: '已取消添加'
							});
						});
				} else {
					console.log('验证失败');
					return false;
				}
			});
		},
		handleDelete(index, deleteId) {
			this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			})
				.then(() => {
					const delId = { id: deleteId };

					deleteRole(deleteId).then(resp => {
						this.$message({
							type: 'success',
							message: '删除成功!'
						});
						this.getRoleList();
					});
				})
				.catch(() => {
					this.$message({
						type: 'error',
						message: '删除失败！'
					});
				});
		},
		onSizeChange(pageSize) {
			this.pageNo = 1;
			this.pageSize = pageSize;
			this.getRoleList();
		},
		onPageChange(page) {
			this.pageNo = page;
			this.getRoleList();
		},
		onClose() {
			this.roleForm = [];
			this.roleAuthList = [];

			this.showAuthMenu = false;
			this.showEditBox = false;
			this.showAddBox = false;
		},

		changeEnableOrLock(row, judge) {
			console.log(row);
			var param = [];
			console.log(judge);
			if (judge) {
				param = { id: row.id, enable: row.enable };
			} else {
				param = { id: row.id, lockable: row.lockable };
			}
			console.log(param);
			addRole(param)
				.then(resp => {
					this.$message({
						type: 'success',
						message: '已修改'
					});
				})
				.catch(ex => {
					this.$message({
						type: 'error',
						message: '修改失败' + ex
					});
				});
		},

		showEdit(row) {
			//设置id
			console.log('row.id-----' + row.id);
			//设置表单默认值
			console.log(row);
			this.roleForm.roleAuth = row.roleAuth;
			this.roleForm.roleDesc = row.roleDesc;
			this.roleForm.roleName = row.roleName;
			console.log('这里是showEdit-----------------');

			console.log(this.roleForm);
			//弹框
			this.showEditBox = true;
		},
		showAuth(row) {
			//此处应该获取的是角色权限的菜单列表
			this.role = row;

			//应该通过row到后台获取权限数据
			showAuth(row).then(resp => {
				console.log('-----------resp.rows-----------');
				console.log(resp.rows);
				if (resp.rows) {
					this.multipleSelection = resp.rows;
					let tableData = this.menuList;
					console.log('-----------------设置选中-----------------');
					tableData.forEach(data => {
						//如果匹配到父级路径
						var fullChildrenFlag = true;
						if (data.children && data.children.length != 0) {
							//如果存在子菜单，通过子菜单id比较
							data.children.forEach(children => {
								if (resp.rows.some(row => row.id === children.id)) {
									this.$refs.tableRef.toggleRowSelection(children, true);
								} else {
									fullChildrenFlag = false;
								}
							});
							if (fullChildrenFlag) {
								this.$refs.tableRef.toggleRowSelection(data, true);
							}
						} else {
							if (resp.rows.some(row => row.id === data.id)) {
								this.$refs.tableRef.toggleRowSelection(data, true);
							}
						}
					});
					console.log('-----------------END-----------------');
				} else {
					this.multipleSelection = [];
				}
			});
			//遍历List，再用this.$refs.tableRef.toggleRowSelection(row);可以形成选择
			this.showAuthMenu = true;
		},
		toggleSelection(rows) {
			if (rows) {
				rows.forEach(row => {
					// console.log(row);
					this.$refs.tableRef.toggleRowSelection(row);
				});
			} else {
				this.$refs.tableRef.clearSelection();
			}
		},
		handleSelectionChange(val) {
			this.multipleSelection = val;
			// 设置多选行数
			// console.log(this.multipleSelection);
		},
		handleAuth(row) {
			//存入权限列表
			const menuIds = [];
			this.multipleSelection.forEach(item => {
				menuIds.push(item.id);
			});
			const param = {
				role: this.role,
				menuIds: menuIds
			};
			changeAuth(param).then(resp => {
				if (resp.success) {
					ElMessage.success('修改成功！');
					this.showAuthMenu = false;
					this.$refs.tableRef.clearSelection();
				}
			});
		},
		//  ---清空编辑框所修改的函数
		clearEdit() {
			//清空表单默认值
			this.roleForm = [];
			this.multipleSelection = [];
			this.$refs.tableRef.clearSelection();

			//关闭弹框

			this.showAuthMenu = false;
			this.showAddBox = false;
			this.showEditBox = false;
		}
	},
	mounted() {
		//组件被挂载自动调用方法
		this.getRoleList();
		const param = { page: '', limit: '' };
		getMenuList(param).then(resp => {
			this.menuList = resp.rows;
		});
	}
};
</script>

<style scoped>
div.el-breadcrumb {
	height: 45px;
}

.el-dialog__body {
	padding: 0px 15px;
}

.el-form-item {
	/* height: 68px; */
}
</style>
